package com.caiyouxi.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.control.BaseController;
import com.caiyouxi.common.exception.BusinessException;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.model.Coupons;
import com.caiyouxi.finance.model.CouponsPayBean;
import com.caiyouxi.finance.service.CouponsService;
import com.caiyouxi.goods.model.GoodsDiscount;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.goods.service.GoodsDiscountsService;
import com.caiyouxi.goods.service.GoodsInfoService;
import com.caiyouxi.order.model.OrderBean;
import com.caiyouxi.order.service.OrderService;
import com.caiyouxi.pay.model.*;
import com.caiyouxi.pay.payment.alipay.AlipayPayService;
import com.caiyouxi.pay.payment.weixin.WxPayService;
import com.caiyouxi.pay.service.AccountPayService;
import com.caiyouxi.pay.service.CouponsPayService;
import com.caiyouxi.pay.service.GoodsDiscountPayService;
import com.caiyouxi.pay.service.PayServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by  on 2015/8/27.
 * 支付相关
 */
@RestController
@RequestMapping("/pay")
public class PayController extends BaseController {

    private Logger logger = Logger.getLogger(PayController.class);

    @Autowired
    private PayServiceImpl payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AccountPayService accountPayService;
    @Autowired
    private GoodsDiscountPayService goodsDiscountPayService;
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private GoodsDiscountsService goodsDiscountsService;
    @Autowired
    private CouponsPayService couponsPayService;
    @Autowired
    private CouponsService couponsService;

    /**
     * 获取支付方式
     * @param request
     * @param response
     * @param bean
     * @return
     */
    @RequestMapping("get_product_payment")
    public ResData get_product_payment(HttpServletRequest request, HttpServletResponse response, @RequestBody PaymentConfigBean bean)
    {
        logger.info("获取产品支付方式,order_id:"+bean.getId());
        List<PaymentConfigBean> list = payService.get_product_payment(bean);

        //获取券信息
        CouponsPayBean cpb = new CouponsPayBean();
        cpb.setFund_type(bean.getTarget_type());
        cpb.setUser_id(bean.getUser_id());
        List<Coupons> coupons = couponsService.get_coupons_usefull_list(cpb);

        //获取折扣
        GoodsInfo goods = goodsInfoService.select_goods_info_by_app_id(bean.getApp_id());
        List<GoodsDiscount> goods_discount = goodsDiscountsService.get_goods_discounts_usefull_list(goods);
        List<GoodsDiscount> g_dis = new ArrayList(); 
        for(GoodsDiscount gd : goods_discount){
            if(goodsDiscountPayService.check_discount(gd,goods,bean.getAmount()/goods.getPrice(),Integer.valueOf(bean.getUser_id()))){
                g_dis.add(gd);
            }
        }

        JSONObject job = new JSONObject();
        job.put("payment_list",list);//支付方式
        if(coupons.size() > 0){
            job.put("coupons_list",coupons);//券
        }
        if(g_dis.size() > 0){
            job.put("goods_discount_list",g_dis);//折扣
        }
        return  success(job);

    }


    /**
     * 第三方支付
     * @param request
     * @param response
     * @param bean
     * @return
     */
    @RequestMapping("gateway_pay")
    public ResData gateway_pay(HttpServletRequest request, HttpServletResponse response, @RequestBody OrderBean bean) throws Exception
    {
        return  payService.get_pay_resp(bean);
    }
    @RequestMapping("get_payment_by_provider")
    public ResData get_payment_by_provider(HttpServletRequest request, HttpServletResponse response, @RequestBody PaymentBean bean)
    {
        return  success(payService.get_payment_by_provider(bean.getProvider()));
    }
    

    /**
     * 支付回调 APP同步回调
     * @param request
     * @param response
     * @param bean
     * @return
     */
    @RequestMapping("app_notify")
    public ResData app_notify(HttpServletRequest request, HttpServletResponse response, @RequestBody OrderBean bean)
    {
        logger.info("APP支付回调,order_id:"+bean.getId()+",code:"+bean.getPay_result());
        if("SUCCESS".equals(bean.getPay_result()))
        {
            //订单处理
            logger.info("APP支付成功");
            try{
//                orderService.process_order_pay_back_success(bean.getId());
            }catch(Exception e){
                Log.d("处理异常");
                return failed("SYS_ERROR", "系统异常",null);
            }
        }
        else
        {
            logger.info("用户支付失败，暂不做下理"+bean.getId());
        }
        return success(null);
    }
    /**
     * 微信支付回调 第三方支付回调
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("wx_notify")
    public ResData wx_notify(HttpServletRequest request, HttpServletResponse response, @RequestBody OrderBean bean)
    {
            return payService.order_process(bean.getId());
    }
    /**
     * 支付宝支付回调 第三方支付回调
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("alipay_notify")
    public ResData alipay_notify(HttpServletRequest request, HttpServletResponse response, @RequestBody OrderBean bean)
    {
        logger.info("***********支付宝异步通知处理——start:");
        return payService.order_process(bean.getId());
    }


    /**
     * 非第三方支付（余额——包括账户余额、平台币、竞猜豆等等）
     */
    @RequestMapping("account_pay")
    public ResData account_pay(HttpServletRequest request, HttpServletResponse response, @RequestBody PayTypeBean payTypebean){
        logger.info("开始进行非第三方支付：start");
        try {
            OrderBean bean = orderService.get_order_by_id(payTypebean.getOrder_id());
            return accountPayService.account_pay(bean);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("非第三方支付异常" + e.getMessage());
            return failed("SYS_ERROR", "系统异常",null);
        }
    }

    /**
     * 支付宝支付
      */
    @RequestMapping("ali_pay")
    public ResData ali_pay(HttpServletRequest request, HttpServletResponse response, @RequestBody PayTypeBean payTypebean){
        logger.info("开始进行非第三方支付：start");
        try {
            //查询支付方式
            OrderBean bean = orderService.get_order_by_id(payTypebean.getOrder_id());
            PaymentConfigBean ppb = payService.get_paymen_config(bean);
            if(null==ppb || "DISABLED".equals(ppb.getStatus()))
            {
                logger.error("支付方式不可用");
                throw new BusinessException(ErrorCode.PAY_INVALID);
            }
            if(!"ALIPAY".equals(ppb.getProvider()))
            {
                logger.error("支付方式不正确");
                throw new BusinessException(ErrorCode.PAY_INVALID);
            }
            //支付宝支付
            GoodsInfo gInfo = goodsInfoService.select_goodsInfo_by_id(Long.valueOf(bean.getGoods_id()));
            JSONObject obj = new AlipayPayService().get_third_pay_resp(payService,bean,gInfo,ppb);
            return success(obj);
        } catch (Exception e) {
            logger.error("支付宝支付异常" + e.getMessage());
            return failed("SYS_ERROR", "系统异常",null);
        }
    }

    /**
     * 微信支付
     */
    @RequestMapping("weixin_pay")
    public ResData weixin_pay(HttpServletRequest request, HttpServletResponse response, @RequestBody PayTypeBean payTypebean){
        logger.info("开始进行非第三方支付：start");
        try {
            //查询支付方式
            OrderBean bean = orderService.get_order_by_id(payTypebean.getOrder_id());
            PaymentConfigBean ppb = payService.get_paymen_config(bean);
            if(null==ppb || "DISABLED".equals(ppb.getStatus()))
            {
                logger.error("支付方式不可用");
                throw new BusinessException(ErrorCode.PAY_INVALID);
            }
            if(!"WECHAT".equals(ppb.getProvider()))
            {
                logger.error("支付方式不正确");
                throw new BusinessException(ErrorCode.PAY_INVALID);
            }
            //微信支付
            GoodsInfo gInfo = goodsInfoService.select_goodsInfo_by_id(Long.valueOf(bean.getGoods_id()));
            JSONObject obj = new WxPayService().get_third_pay_resp(payService,bean,gInfo,ppb);
            return success(obj);
        } catch (Exception e) {
            logger.error("微信支付异常" + e.getMessage());
            return failed("SYS_ERROR", "系统异常",null);
        }
    }

    /**
     * 支付
     */
    @RequestMapping("app_pay")
    public ResData app_pay(HttpServletRequest request, HttpServletResponse response, @RequestBody PayTypeBean bean){
        OrderBean order = orderService.get_order_by_id(bean.getOrder_id());
        if("ACCOUNT".equals(bean.getProvider())){
            try{
                accountPayService.account_pay(order);
            }catch(Exception e){
                Log.d("余额支付异常" + e.getMessage());
                return failed("SYS_ERROR", "系统异常",null);
            }
        }else{
            try{
                payService.get_pay_resp(order);
            }catch(Exception e){
                Log.d("第三方支付异常" + e.getMessage());
                return failed("SYS_ERROR", "系统异常",null);
            }
        }
        return success(null);
    }

    /**
     * 统一支付服务
     * provider(wx.zfb.account)
     * goods_discount_id
     * coupon_ids
     * order_id
     *
     *
     */
    @RequestMapping("pay")
    public ResData pay(HttpServletRequest request, HttpServletResponse response, @RequestBody PayTypeBean bean){

        Log.d("统一支付服务，ORDER_ID："+bean.getOrder_id());
        return payService.pay(bean);

    }

    /**
     * 获取对应的计算后的金额
     */
    @RequestMapping("get_result_amount")
    public ResData get_result_amount(HttpServletRequest request, HttpServletResponse response, @RequestBody PayAmountBean bean){
        Integer tolamount = bean.getAmount();
        GoodsInfo gInfo = goodsInfoService.select_goods_info_by_app_id(bean.getApp_id());
        if(gInfo == null){
            //商品不存在
            Log.e("商品不存在");
            return failed("SYS_ERROR", "系统异常",null);
        }
        PayAmountResultBean parb = new PayAmountResultBean();
        Integer dis_amount = tolamount;//折扣消费前的金额
        try{
            //先算折扣
            GoodsDiscount goodsDiscount = goodsDiscountsService.get_goods_discounts(gInfo);
            if(!StringUtils.isEmpty(bean.getGoods_discount()) && !"0".equals(bean.getGoods_discount()) && goodsDiscount != null){
                if(bean.getGoods_discount().equals(goodsDiscount.getId().toString())){
                    boolean flag = goodsDiscountPayService.check_discount(goodsDiscount,gInfo,bean.getAmount()/gInfo.getPrice(),Integer.valueOf(bean.getUser_id()));
                    if(flag){
                        //校验通过，享受折扣
                        tolamount = tolamount * goodsDiscount.getDiscount() / 100;//剩余支付金额
                    }
                }else{
                    Log.d("传过来的折扣id与商品对应可用的折扣id不符");
                    return failed("SYS_ERROR", "系统异常",null);
                }
            }
        }catch(Exception e){
            Log.d("折扣计算异常" + e.getMessage());
            e.printStackTrace();
            return failed("SYS_ERROR", "系统异常",null);
        }
        parb.setDiscount_amount(String.valueOf((dis_amount - tolamount)/100.00));//享受折扣金额
        Integer cou_amount = tolamount;//券消费前的金额
        try{
            if(!StringUtils.isEmpty(bean.getCoupon_ids()) && !"null".equals(bean.getCoupon_ids())){
                String[] coupons_ids = bean.getCoupon_ids().split(",");
                for(String coupons_id : coupons_ids){
                    if(coupons_id != null && !"".equals(coupons_id)){
                        if(tolamount != 0){
                            tolamount = couponsPayService.coupons_on_use(coupons_id,bean.getFund_type(),tolamount,null,null,Integer.valueOf(bean.getUser_id()),gInfo,false);
                        }else{
                            //无需用券
                            Log.d(bean.getFund_type() + "无需用券");
                            return success(tolamount);
                        }
                    }
                }
            }
        }catch(Exception e){
            Log.d("券计算异常" + e.getMessage());
            return failed("SYS_ERROR", "系统异常",null);
        }
        parb.setCoupons_amount(String.valueOf((cou_amount - tolamount)/100.00));//消费的券金额
        parb.setLow_amount(String.valueOf(tolamount /100.00));//剩余待支付的金额
        return success(parb);
    }
}
